package jm.mq.bootconfirm.conf;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Description 消息处理回调接口
 * @date 2022/3/13 9:45
 */
@Slf4j
@Component
public class CallBackConf implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 将当前类注入到 setConfirmCallback 中
     * 将当前类注入到 setReturnsCallback 中
     */
    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * 确认回调
     * @param correlationData 保存回调消息ID及相关内容
     * @param ack 是否接收成功
     * @param cause 失败原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String msgId = correlationData != null ? correlationData.getId() : "";
        if (ack) {
            log.info("接收消息成功，ID：{}", msgId);
        }else {
            log.error("接收消息失败，原因：{}，ID：{}",cause,msgId);
        }
    }

    /**
     * 接收失败回退消息
     * @param returned 回退对象
     */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.error("\n消息：{}\n被交换机{}回退：\n原因：{}，\nRoutingKey：{}",
                returned.getMessage(),
                returned.getExchange(),
                returned.getReplyText(),
                returned.getRoutingKey());
    }
}
